package com.thinkgem.jeesite.modules.university.utils;

import java.util.List;

import com.thinkgem.jeesite.common.utils.SpringContextHolder;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.university.entity.UniversityOrg;
import com.thinkgem.jeesite.modules.university.service.UniversityOrgService;

public class UniversityOrgUtils {
	
	private static UniversityOrgService universityOrgService = SpringContextHolder.getBean(UniversityOrgService.class);

	public static final UniversityOrg TOP_ORG_NODE;
	public static final String TOP_NODE_ID = "0";
	public static final String TOP_NODE_CODE = "100";
	public static final Integer DEFAULT_SORT = 30;
	
	static{
		TOP_ORG_NODE = new UniversityOrg(TOP_NODE_ID);
		TOP_ORG_NODE.setCode(TOP_NODE_CODE);
	}
	/**
	 * 自动设置Sort And Code
	 * @param universityOrg
	 */
	public static void setSortAndCode(UniversityOrg universityOrg) {
		
		if (universityOrg.getParent()==null || StringUtils.isBlank(universityOrg.getParent().getId())){
			//无父节点
			universityOrg.setParent(TOP_ORG_NODE);
		}else if(UniversityOrgUtils.TOP_NODE_ID.equals(universityOrg.getParent().getId())){
			//父节点Id为"0"
			universityOrg.getParent().setCode(TOP_NODE_CODE);
		}else{
			universityOrg.setParent(universityOrgService.get(universityOrg.getParent().getId()));
			
		}
		if (StringUtils.isBlank(universityOrg.getId())&&universityOrg.getParent()!=null){
			// 获取排序号，最末节点排序号+30
			UniversityOrg org = new UniversityOrg();
			org.setParent(universityOrg.getParent());
			List<UniversityOrg> list = universityOrgService.findList(org); 

			if (list.size() > 0){
				universityOrg.setSort(list.get(list.size()-1).getSort());
				if (universityOrg.getSort() != null){
					universityOrg.setSort(universityOrg.getSort() + 30);
				}
			}
			
			int size = 0;
			for (int i=0; i<list.size(); i++){
				size++;
			}
			universityOrg.setCode(universityOrg.getParent().getCode() + StringUtils.leftPad(String.valueOf(size > 0 ? size+1 : 1), 3, "0"));
		}

		if (universityOrg.getSort() == null){
			universityOrg.setSort(DEFAULT_SORT);
		}
	}
	
	/**
	 * 判断此节点是否存在
	 * @param universityOrg
	 * @param name
	 * @return
	 */
	public static Boolean exist(UniversityOrg universityOrg){
		if(universityOrg == null || StringUtils.isBlank(universityOrg.getName())){
			return null;
		}
		//没有父节点 默认类型为大学
		if(universityOrg.getParent() == null){
			universityOrg.setParent(TOP_ORG_NODE);
		}
		//只保留一个parent属性 查询parent下子节点集合
		UniversityOrg org = new UniversityOrg();
		org.setParent(universityOrg.getParent());
		List<UniversityOrg> childList = universityOrgService.findList(org);
		if (childList != null && childList.size() > 0){
			for (UniversityOrg child : childList) {
				if(child.getName().equals(universityOrg.getName())){
					//此节点已经存在
					return true;
				}
			}
		}
		return false;
	}

}
